<template>
  <el-dialog
    v-model="uploadVisible"
    :title="$t('common.uploadFiles')"
    width="500px"
    @close="uploadClosed"
  >
    <el-upload
      ref="uploadRef"
      drag
      :action="action"
      :headers="headers"
      :data="requestData"
      multiple
      :on-success="uploadSuccess"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        {{ $t("common.dragFiles") }}
        <em>{{ $t("common.uploadEvent") }}</em>
      </div>
      <template #tip>
        <div class="el-upload__tip" @click="templateDown">
          <a style="color: var(--el-color-primary)">{{ templateTitle }}</a>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="uploadClosed">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" @click="submitUpload">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { useUserStoreHook } from "@/stores/modules/user";
import type { UploadInstance } from "element-plus";
import { fileApi } from "@/api/file";

// 导入类型
interface importType {
  tenant: string;
  requestId: string;
  fileNames: string;
  updateMask: string;
  addFlag: boolean;
}
// 上传文件的地址
const action = ref(fileApi.uploadUrl());
// 请求上传的头部
const headers = ref({ Authorization: "Bearer " + useUserStoreHook().token });
const requestData = reactive({
  tenant: useUserStoreHook().user.tenant
});
const uploadRef = ref<UploadInstance>();
const importData: importType = reactive({
  tenant: useUserStoreHook().user.tenant,
  requestId: Math.random() * 10 + "",
  fileNames: "",
  updateMask: "",
  addFlag: true // 必填项，true新增，false修改
});
const props = defineProps({
  uploadVisible: {
    type: Boolean,
    default: () => false
  },
  templateTitle: {
    type: String,
    default: ""
  }
});
const emits = defineEmits(["templateDown", "importEvents", "uploadClosed"]);
const { uploadVisible } = toRefs(props);

function templateDown() {
  emits("templateDown");
}

function uploadSuccess(res: any) {
  console.log(res);
  importData.fileNames = res.fileSrc;
  if (importData.fileNames) {
    ElMessage({
      message: t("common.uploadSuccess"),
      type: "success"
    });
  }
}

function submitUpload() {
  emits("importEvents", importData);
}

function uploadClosed() {
  emits("uploadClosed");
}
</script>
